package com.bifrost.service.impl;

import com.bifrost.common.base.ServerResponse;
import com.bifrost.entity.Customer;
import com.bifrost.entity.CustomerType;
import com.bifrost.entity.MerchantStore;
import com.bifrost.model.ro.CustomerRO;
import com.bifrost.model.vo.CustomerVO;
import com.bifrost.model.vo.PageVO;
import com.bifrost.repository.CustomerRepository;
import com.bifrost.service.CustomerManageService;
import com.bifrost.util.DateUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.*;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

@Service
public class CustomerManageServiceImpl implements CustomerManageService {
    @Autowired
    private CustomerRepository customerRepository;

    /**
     * 获取所有客户基本信息
     * @param name
     * @param isActive
     * @param customerTypeName :查询条件
     * @param loyaltyCard
     * @param merchantStoreIdList
     * @param pageCode ：当前页
     * @param pageSize ：单页显示条数    @return                      */
    @Override
    public ServerResponse findCustomerModels(String name, String isActive, String customerTypeName, String loyaltyCard, List<Long> merchantStoreIdList, Integer pageCode, Integer pageSize) throws UnsupportedEncodingException {
        Pageable pageable = new PageRequest(pageCode-1,pageSize);
        Specification<Customer> specification = new Specification<Customer>() {
            @Override
            public Predicate toPredicate(Root<Customer> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> predicates = new ArrayList<>();
                //先判null,在判空
                if(StringUtils.isNotBlank(name)){
                    //添加查询条件
                    predicates.add(cb.like(root.get("customerLastname"),"%".concat(name.trim()).concat("%")));
                }
                //增加查询添加是否激活
                if(isActive != null && !isActive.trim().isEmpty()){
                    if(Boolean.TRUE.toString().equalsIgnoreCase(isActive)){
                        predicates.add(cb.equal(root.get("isActive"),Boolean.TRUE));
                    }else{
                        predicates.add(cb.equal(root.get("isActive"),Boolean.FALSE));
                    }
                }
                //增加查询条件会员类型
                if(StringUtils.isNotBlank(customerTypeName)){
                    //两张表关联查询
                    Join<Customer,CustomerType> join = root.join("customerType", JoinType.INNER);
                    Path<String> customerType = join.get("name");
                    predicates.add(cb.like(customerType, "%".concat(customerTypeName.trim()).concat("%")));
                }
                //增加查询条件，会员卡号
                if(StringUtils.isNotBlank(loyaltyCard)){
                    predicates.add(cb.like(root.get("loyaltyCard"),"%"+loyaltyCard.trim()+"%"));
                }
                if(CollectionUtils.isNotEmpty(merchantStoreIdList)){
                    Join<Customer,MerchantStore> join = root.join("merchantStore", JoinType.INNER);
                    Path<Long> merchantStoreId = join.get("merchantId");
                    CriteriaBuilder.In<Long> in = cb.in(merchantStoreId);
                    for(Long id : merchantStoreIdList){
                        in.value(id);
                    }
                    predicates.add(in);
                }
                //只显示有会员卡号的
                predicates.add(cb.isNotNull(root.get("loyaltyCard")));
                Predicate[] p = new Predicate[predicates.size()];
                return cb.and(predicates.toArray(p));
            }
        };
        Page<Customer> customers = customerRepository.findAll(specification,pageable);
        //判断是否有数据
        if (CollectionUtils.isEmpty(customers.getContent())) {
            return ServerResponse.createByErrorMsg("没有数据");
        }
        //获取总的数据个数
        Long totalElements = customers.getTotalElements();
        //将获取到的数据存入customerVO集合中
        List<CustomerVO> customerVOList = new ArrayList<CustomerVO>();
        for(Customer customer : customers){
            CustomerVO customerVO = new CustomerVO();
            //设置客户基本信息
            BeanUtils.copyProperties(customer,customerVO);
            customerVO.setCreatedTimestamp(DateUtils.formatDate(customer.getCreatedTimestamp(), DateUtils.DEFAULT_DATE_FORMAT));
            customerVO.setActive(customer.isActive());
            //获取订单的门店信息
            MerchantStore merchantStore = customer.getMerchantStore();
            if(merchantStore != null){
                customerVO.setMerchantMessage("["+merchantStore.getExternalId()+"]"+merchantStore.getStoreName());
            }
            //设置客户类型名称
            CustomerType customerType = customer.getCustomerType();
            if(customerType != null){
                customerVO.setCustomerType(customerType.getName());
            }
            customerVOList.add(customerVO);
        }
        PageVO pageVO = new PageVO(pageCode,pageSize,totalElements.intValue(),customerVOList);
        return ServerResponse.createBySuccess(pageVO);
    }

    /**
     * 根据会员的明确信息查询单个会员
     * @param customerRO
     * @return
     */
    @Override
    public CustomerVO findOneCustomer(CustomerRO customerRO) {
        Specification<Customer> specification = new Specification<Customer>() {
            @Override
            public Predicate toPredicate(Root<Customer> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> predicates = new ArrayList<>();
                //增加查询条件会员卡号
                if(StringUtils.isNotBlank(customerRO.getLoyaltyCard())){
                    predicates.add(cb.equal(root.get("loyaltyCard"),customerRO.getLoyaltyCard()));
                }
                Predicate[] p = new Predicate[predicates.size()];
                return cb.and(predicates.toArray(p));
            }
        };
        List<Customer> customerList = customerRepository.findAll(specification);
        if(CollectionUtils.isNotEmpty(customerList)){
            CustomerVO customerVO = new CustomerVO();
            //只返回第一个
            BeanUtils.copyProperties(customerList.get(0),customerVO);
            return customerVO;
        }
        return null;
    }

}
